package org.kojo.tdrm.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.kojo.tdrm.dao.UserDao;
import org.kojo.tdrm.entity.Task;
import org.kojo.tdrm.entity.User;
import org.kojo.tdrm.entity.UserConf;
import org.kojo.tdrm.persistence.PMF;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class UserAppService {
	private static Logger log = Logger.getLogger(UserAppService.class.getName());
	public void createUser(User user) {
		UserDao dao = new UserDao(User.class);
		dao.create(user);
	}

	public void updateUser(User user) {
		UserDao dao = new UserDao(User.class);
		dao.edit(user);
	}
	
	public List<User> findAll(){
		UserDao dao = new UserDao(User.class);
		return dao.findAll();
	}

	public User findUser(String userid) {
		User u = null;
		UserDao dao = new UserDao(User.class);
		u = dao.find(userid);
		return u;
	}
	
	public UserConf findUserConf(String userid){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		UserConf uc = null;
		User u = pm.getObjectById(User.class,userid);
		pm.retrieve(u);
		uc = u.getUserConf();
		log.fine("login["+userid+"] find user config found -> "+uc);
		if(uc==null){
			uc = new UserConf();
		}
		pm.close();
		return uc;
		
	}
	
	public void saveUserConf(String userId,UserConf uc){
		uc.setLastUpdate(new Date());
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		User u = pm.getObjectById(User.class, userId);
		pm.retrieve(u);
		UserConf current = u.getUserConf();
		if(current==null){
			current = uc;
			u.setUserConf(current);
		} else {
			current.setReminderTime(uc.getReminderTime());
			current.setReminderUnit(uc.getReminderUnit());
		}
		log.fine("login["+userId+"] save user config remt="+current.getReminderTime());
		pm.currentTransaction().begin();
		pm.makePersistent(u);
		pm.currentTransaction().commit();
		pm.close();
	}

}
